package org.dg.iag.server;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.dg.iag.dao.GenericDAO;
import org.dg.iag.query.XQueryGet;
import org.dg.iag.query.XQueryUtil;
import org.dg.iag.util.ApplicationConstants;
import org.dg.iag.util.RestletUtil;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;

public class EntityServerResource extends ServerResource {
	@Get
	public Object getEntityList() {
		
		String entity					= RestletUtil.getPathFromRequest(getRequest(), "entityName");
		
		HashMap<String, String> params	= new HashMap<String, String>();
		
		RestletUtil.populateParamsMap(params, getRequest());
		
		
		GenericDAO<Object, Object> gdao	= new GenericDAO<Object, Object>(ApplicationConstants.IATI_STORAGE_PATH);
		String format					= params.remove("format");
		
		XQueryGet xqg;
		if ( entity != null) {
			boolean requestingActivity	= "/".equals(entity);
			if (requestingActivity)
				entity	= "";
			if ( params.size() == 0 ) {
				xqg					= new XQueryGet("", 
						"<query-results>{/iati-activities/iati-activity"+entity+
								"}</query-results>", 
						false);
			}
			else {
				Map<String,String> relConditions  	= new HashMap<String, String>();
				Map<String,String> absConditions  	= new HashMap<String, String>();
				String relConditionStr				= "";
				String absConditionStr				= "";
				for (Entry<String,String> e:params.entrySet() ) {
					
					if ( e.getKey().startsWith("/") && requestingActivity ) {
						absConditions.put(e.getKey().substring(1), e.getValue());
					}
					else {
						relConditions.put(e.getKey(), e.getValue());
					}
					
				}
				if ( absConditions.size() > 0 ) {
					absConditionStr	= XQueryUtil.generateXpathCondition(absConditions, true);
				}
				if ( relConditions.size() > 0 ) {
					relConditionStr	= XQueryUtil.generateXpathCondition(relConditions, true);
				}
				xqg					= new XQueryGet("", 
							"<query-results>{/iati-activities/iati-activity"+absConditionStr+entity+relConditionStr +
									"}</query-results>", 
							false);
			}
			
			String ret						= gdao.getElementsAsString(xqg);
			if (format != null && "json".equals( format ) ) {
				ret		= RestletUtil.generateJsonFromXML(ret);
			}
			
			
			return ret;
		}
		return "Nothing found";
	}
}
